<template>
  <el-dialog v-model="visible" title="添加设备" @close="device = {}">
    <el-form ref="formRef" :model="device" :rules="rules" label-width="100px">
      <el-form-item label="设备名称" prop="company_device_name">
        <el-input v-model="device.company_device_name"/>
      </el-form-item>
      <el-form-item label="设备型号" prop="company_device_xh">
        <el-input v-model="device.company_device_xh"/>
      </el-form-item>
      <el-form-item label="所属公司" prop="company_id">
        <company-selector v-model="device.company_id"/>
      </el-form-item>
      <el-form-item label="标定时间" prop="company_device_time">
        <el-date-picker v-model="device.company_device_time"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="选择日期"/>
      </el-form-item>
      <el-form-item label="设备购买发票" prop="company_device_device_fp">
        <image-uploader v-model="device.company_device_device_fp" v-model:company-id="device.company_id"
                        alt="设备购买发票"/>
      </el-form-item>
      <el-form-item label="标定证书上传" prop="company_device_device_img">
        <file-uploader v-model="device.company_device_device_img" v-model:company-id="device.company_id"
                       alt="标定证书上传"/>
      </el-form-item>
      <el-form-item>
        <el-button class="ml-auto" @click="submitForm" v-loading="isLoading" type="primary">添加</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup lang="ts">
import {reactive, ref, useTemplateRef} from "vue";
import type {DeviceVO} from "../../../types";
import CompanySelector from "../../../components/CompanySelector.vue";
import {useMutation} from "@pinia/colada";
import {insertDevice} from "../../../api/device.ts";
import {ElMessage, type FormInstance, type FormRules} from "element-plus"
import ImageUploader from "../../../components/ImageUploader.vue";
import FileUploader from "../../../components/FileUploader.vue";

const visible = defineModel({
  default: false
})

const emits = defineEmits<{
  success: []
}>();

const device = ref<DeviceVO>({})

const rules = reactive<FormRules<DeviceVO>>({
  company_id: [
    {required: true, message: "请选择所属公司"}
  ],
  company_device_name: [
    {required: true, message: "请输入设备编号"}
  ]
})

const formRef = useTemplateRef<FormInstance>("formRef")

const submitForm = async () => {
  await formRef.value?.validate((valid) => {
    if (valid) {
      insertDeviceFn(device.value)
    }
  })
}

let {mutate: insertDeviceFn, isLoading} = useMutation({
  mutation: (device: DeviceVO) => insertDevice(device),
  onSuccess: () => {
    visible.value = false
    emits("success")
    ElMessage.success("添加成功")
  }
});
</script>

<style scoped>

</style>